package com.identify.identifydrawings;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;

import com.bumptech.glide.signature.ObjectKey;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.identify.identifydrawings.netUtils.JsonUtils;
import com.identify.identifydrawings.netUtils.Url;
import com.jhuster.imagecropper.CropIntent;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;
import com.yanzhenjie.album.AlbumFile;
import com.yanzhenjie.album.api.widget.Widget;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class MainActivity extends BaseActivity {
    // 申请权限的集合，同时要在AndroidManifest.xml中申请，Android 6以上需要动态申请权限
    String[] permissions = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET
    };
    // 声明一个集合，在后面的代码中用来存储用户拒绝授权的权
    List<String> mPermissionList = new ArrayList<>();
    ImageView img, imgdetect;
//    ImageView imgcut;
    //ImageView imgSearch;
    Button bt_cut,btn;
    //EditText tvCode;
    //PhotoView photoView;
    File f;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = findViewById(R.id.img);
        imgdetect = findViewById(R.id.imgdetect);
//        imgcut = findViewById(R.id.imgcut);
        // imgSearch  = findViewById(R.id.imgSearch);
        //tvCode = findViewById(R.id.tvCode);
        bt_cut=findViewById(R.id.photocut);

//        btn = findViewById(R.id.btn_popMenu);
//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                showPopMenu(view);
//            }
//
//        });
        //tvCode1 = findViewById(R.id.tvCode1);
       // photoView = (PhotoView) findViewById(R.id.imgSearch);
        // 启用图片缩放功能
       // photoView.enable();
        Album.initialize(AlbumConfig.newBuilder(this)
                .setAlbumLoader(new MediaLoader())
                .build());
        //initOcr();

    }
//        public void showPopMenu(View view){
//            PopupMenu menu = new PopupMenu(this,view);
//            menu.getMenuInflater().inflate(R.menu.main_menu,menu.getMenu());
//            menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
//                @Override
//                public boolean onMenuItemClick(MenuItem item) {
//                    switch (item.getItemId()){
//                        case R.id.add_item:
//                            Toast.makeText(MainActivity.this, "手动裁剪 selected", Toast.LENGTH_SHORT).show();
//                            Intent intent=new Intent(MainActivity.this, ManualCutting.class);
//                            startActivity(intent);
//                            break;
//
//                        case R.id.delete_item:
//                            Toast.makeText(MainActivity.this, "Delete Selected", Toast.LENGTH_SHORT).show();
//                            break;
//
//                    }
//                    return true;
//                }
//            });
//            menu.setOnDismissListener(new PopupMenu.OnDismissListener() {
//                @Override
//                public void onDismiss(PopupMenu menu) {
//                    Toast.makeText(MainActivity.this, "关闭了", Toast.LENGTH_SHORT).show();
//                }
//            });
//            menu.show();
//        }


    private boolean hasGotToken;//是否設置orc成功

    /**
     * 初始化 orc
     */
    private void initOcr() {
        OCR.getInstance(this).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                hasGotToken = true;
                Log.e("TAG  AK，SK方式获取token成功", "token=" + token);
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                Log.e("TAG  AK，SK方式获取token失败", error.getMessage());
            }
        }, getApplicationContext(), "4p2Xng7gIhFRU9nhUGjZWd2p", "w31GOoyvs5ArTp2VTsEseBfqpGspllKy");
    }
//裁剪按钮

   // });

    //拍照
    public void takePhoto(View view) {
        Album.camera(this)
                .image()
                .onResult(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                        startCropImage(result);
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                    }
                })
                .start();
    }
     //相册选择图片
    public void choosePhoto(View view) {
        Album.image(this)
                .singleChoice()
                .columnCount(2)
                .camera(false)
                .widget(
                        Widget.newDarkBuilder(this)
                                .title("选择图片")
                                .statusBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                                .toolBarColor(ContextCompat.getColor(this, R.color.colorPrimary))
                                .build()
                )
                .onResult(new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        if (result == null || result.size() == 0) {
                            return;
                        }
                        startCropImage(result.get(0).getPath());
                    }
                })
                .onCancel(new Action<String>() {
                    @Override
                    public void onAction(@NonNull String result) {
                    }
                })
                .start();
    }

    File corpFile;

    //1. Using the CropIntent to help build the start intent
    private void startCropImage(String path) {
        Log.e("TAG", "startCropImagepath=" + path);
        // Create a CropIntent
        CropIntent intent = new CropIntent();

        // Set the source image filepath/URL and output filepath/URL (Optional)
        intent.setImagePath(path);
        String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaaaa";
        final File file = new File(dirName);
        if (!file.exists()) {
            file.mkdir();
        }

        corpFile = new File(dirName + "/" + "corp.png");
        intent.setOutputPath(corpFile.getAbsolutePath());

        // Set a fixed crop window size (Optional)
        //intent.setOutputSize(640,480);

        // set the max crop window size (Optional)
        //intent.setMaxOutputSize(800,600);

        // Set a fixed crop window's width/height aspect (Optional)
        //intent.setAspect(3,2);

        // start ImageCropper activity with certain request code and listen for result
        startActivityForResult(intent.getIntent(this), 0);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == 0) {
            Uri croppedUri = data.getExtras().getParcelable(MediaStore.EXTRA_OUTPUT);
            if (croppedUri == null) {
                return;
            }
            InputStream in = null;
            try {
                in = getContentResolver().openInputStream(croppedUri);
                Bitmap b = BitmapFactory.decodeStream(in);
                updateImg(b);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //根据选择的图片进行检测显示检测结果
    private String path1;

    private void detect() {
        //6.0获取多个权限
        mPermissionList.clear();
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        //未授予的权限为空，表示都授予了
        if (mPermissionList.isEmpty()) {
            //读取根目录下的一张图片
            path1 = corpFile.getAbsolutePath();
            Log.e("TAG", "f=" + path1);
            boolean fileExist = fileIsExists(path1);
            Log.e("TAG", "fileExist=" + fileExist);
            if (fileExist) {
                //Toast.makeText(MainActivity.this,"开始上传"+f.getAbsolutePath(),Toast.LENGTH_LONG).show();
                try {
                    //上传图片
                    ImageUpload.run(f, new ResponseListener() {
                        @Override
                        public void onResonse(final String response) {
                            Log.e("TAG","MainActivity response="+response);//nishuo
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (TextUtils.isEmpty(response)) {
                                        Toast.makeText(MainActivity.this, "没有返回", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Log.e("TAG", "detectresponse=" + response);
                                        Glide.with(MainActivity.this)
                                                .load(response)
                                                .signature(new ObjectKey(System.currentTimeMillis()))
                                                .into(imgdetect);

                                    }
                                }
                            });

                        }

                        @Override
                        public void onFail(String code, String msg) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //readImg(showImg);
        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);
            ActivityCompat.requestPermissions(MainActivity.this, permissions, 1);
        }
    }
    //获取裁剪图片路径
    public static List<String> filedata=new ArrayList<>();
    private void detectcut() {
        try {
            //上传图片
            ImageUploadCut.run(new ResponseListener() {
                @Override
                public void onResonse(final String response) {

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (TextUtils.isEmpty(response)) {
                                Toast.makeText(MainActivity.this, "没有返回", Toast.LENGTH_SHORT).show();
                            } else {
                                File file = new File(response);//定义一个file对象，用来初始化FileReader
                                FileReader reader = null;//定义一个fileReader对象，用来初始化BufferedReader
                                try {
                                    reader = new FileReader(file);
                                    BufferedReader bReader = new BufferedReader(reader);//new一个BufferedReader对象，将文件内容读取到缓存
                                    StringBuilder sb = new StringBuilder();//定义一个字符串缓存，将字符串存放缓存中
                                    String s = "";
                                    while ((s = bReader.readLine()) != null) {//逐行读取文件内容，不读取换行符和末尾的空格
                                        sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
                                        System.out.println(s);
                                    }
                                    bReader.close();
                                    String str = sb.toString();
                                    Log.e("TAG", "String=" + str);
//gson
                                    Gson gson = new Gson();
                                    TestBean data = gson.fromJson(str, TestBean.class);
                                    List<String> pathcut = data.getPath();
                                    for (int i = 0; i < pathcut.size(); i++) {
                                        Log.e("TAG", "Stringpathcut=" + pathcut.get(i));
                                        String cut=pathcut.get(i);
                                        ImageUploadAdress.run(cut, new ResponseListener() {
                                            @Override
                                            public void onResonse(final String response) {
                                                Log.e("TAG","MainActivity response="+response);//nishuo
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        if (TextUtils.isEmpty(response)) {
                                                            Toast.makeText(MainActivity.this, "没有返回", Toast.LENGTH_SHORT).show();
                                                        } else {
                                                            Log.e("TAG", "detectresponse1=" + response);
//                                                            Glide.with(MainActivity.this)
//                                                                    .load(response)
//                                                                    .signature(new ObjectKey(System.currentTimeMillis()))
//File f=new File();                                                  .into(imgcut);
                                                            filedata.add(response);

                                                        }
                                                    }
                                                });

                                            }
                                            @Override
                                            public void onFail(String code, String msg) {

                                            }
                                        });
                                    }

                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });

                }
                @Override
                public void onFail(String code, String msg) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
//        filedata.clear();
    }
    //检测的图片路径是否存在
    public boolean fileIsExists(String strFile) {
        try {
            f = new File(strFile);
            if (!f.exists()) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 回显图片，识别成果以及是否修改
     *
     * @param path
     */
    private void updateImg(Bitmap path) {
//        Glide.with(this)
//                .load(path)
//                .into(img);

        img.setImageBitmap(path);
        detect();
        Log.e("TAG", "oldfiledata=" + filedata);
        filedata.clear();
        detectcut();
        Log.e("TAG", "newfiledata=" + filedata);
        //vertify(corpFile.getAbsolutePath());

        //刚才file1 是一个方法的局部变量 在外层是访问不到的
        //set  是设置 get是获取
        //logcat是打印日志
    }

    public void cut(View view){
//        detectcut();
        Intent intent=new Intent(MainActivity.this, Search.class);
        startActivity(intent);

    }
    private String TAG = "TAG";


//    //识别算法
//    public void vertify(String path) {
//        //操作
//        final StringBuilder resultStr = new StringBuilder();
//        RecognizeService.recAccurateBasic(this, path,
//                new RecognizeService.ServiceListener() {
//                    @Override
//                    public void onResult(String result) {
//                        Log.e("TAG", "recAccurateBasic  result=" + result);
//                        VertifyData vertifyData = JsonUtils.parseJsonToBean(result, VertifyData.class);
//                        Log.e("TAG", "recAccurateBasic  vertifyData=" + vertifyData);
//                        if (vertifyData == null || vertifyData.getWords_result() == null || vertifyData.getWords_result().size() <= 0) {
//                            setVertifyResult(resultStr.toString());
//                        } else {
//                            for (int i = 0; i < vertifyData.getWords_result().size(); i++) {
//                                resultStr.append(vertifyData.getWords_result().get(i).getWords());
//                            }
//                            resultStr.append(".png");
//                            setVertifyResult(resultStr.toString());
//                        }
//                    }
//                });
////        return "12L104(三)-316.png";
//    }
//
//    private void setVertifyResult(String vertify) {
//        if (TextUtils.isEmpty(vertify)) {
//            Log.e("TAG", "识别失败");
//            tvCode.setText("识别失败,请手动输入");
//        } else {
//            Log.e("TAG", "识别成功=" + vertify);
//            tvCode.setText(vertify);
//        }
//    }

    //搜索
//    public void searchImg(View view) {
////        //oss
////        //返回图片
////        //imgSearch
////        String text = tvCode.getText().toString();
////        getImage(text);
////    }

//    //獲取token
//    private String getImage(String e_account) {
//        String results = null;
//        HashMap map = new HashMap();
//        //?Action=AssumeRole&&RoleArn=acs:ram::1843770436407740:role/AliyunOSSTokenGeneratorRole&RoleSessionName=banyaolian
//        map.put("e_account", e_account);
//
//        OkHttpClient client = new OkHttpClient();
//        final Request request = new Request.Builder()
//                .get()
//                .url(Url.getFileFormNet + "?e_account=" + e_account)
//                .build();
//        Call call = client.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.e("TAG", "onFailure: " + e.getMessage());
//                ;
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                //  String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/LungFile";
//                Log.e("TAG", "response=" + response);
//
//                int code = response.code();
//                if (code != 200) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(MainActivity.this, "key值不对", Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                    return;
//                }
//                String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaaaa";
//
//                final File file = new File(dirName);
//                if (!file.exists()) {
//                    file.mkdir();
//                }
//
//                File file1 = new File(dirName + "/" + "facenew1.png");
//                if (response != null) {
//                    InputStream is = response.body().byteStream();
//                    FileOutputStream fos = new FileOutputStream(file1);
//                    int len = 0;
//                    byte[] buffer = new byte[2048];
//                    while (-1 != (len = is.read(buffer))) {
//                        fos.write(buffer, 0, len);
//                    }
//                    fos.flush();
//                    fos.close();
//                    is.close();
//                }
//                setImg(file1);
//            }
//        });
//        return results;
//    }

    /**
     * 加载图片
     *
     * @param file
     */
//    private void setImg(final File file) {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                Glide.with(MainActivity.this)
//                        .load(file.getAbsolutePath())
//                        .into(photoView);
//            }
//        });
//        // 获取图片信息
//        //  Info info = photoView.getInfo();
//// 从普通的ImageView中获取Info
//        //Info info = PhotoView.getImageViewInfo(ImageView);
//// 从一张图片信息变化到现在的图片，用于图片点击后放大浏览，具体使用可以参照demo的使用
//        //photoView.animaFrom(info);
//// 从现在的图片变化到所给定的图片信息，用于图片放大后点击缩小到原来的位置，具体使用可以参照demo的使用
////        photoView.animaTo(info,new Runnable() {
////            @Override
////            public void run() {
////                //动画完成监听
////            }
////        });
//// 获取/设置 动画持续时间
//        //photoView.setAnimaDuring(1000);
//        int d = photoView.getAnimaDuring();
//// 获取/设置 最大缩放倍数
//        // photoView.setMaxScale(2);
//        //  float maxScale = photoView.getMaxScale();
//// 设置动画的插入器
//        // photoView.setInterpolator(Interpolator interpolator);
//
//
//    }
}
